<?php

namespace App\Repositories\Eloquent\Mgt;

use Illuminate\Container\Container as App;
use App\Repositories\Eloquent\Repository;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\Curl;
use App\Repositories\Eloquent\Mgt\UserRepository as User;
use DB;

class BookRepository extends Repository
{

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Mgt\Book';
    }

    /**
     * 获取书籍列表
     *
     * @param string $query
     * @return mixed
     */
    public function index($query = '')
    {
        if (!$query) {
            $result = $this->model->with('borrows')->withCount('borrows')
                ->orderBy('order')
                ->orderBy('updated_at','desc')
                ->orderBy('id', 'desc');

        } else {
            if (preg_match('/^\d+$/i', $query)) {
                $result = $this->model->with('borrows')
                    ->where('isbn', 'like', "%$query%")
                    ->orderBy('order')
                    ->orderBy('updated_at','desc')
                    ->orderBy('id', 'desc');
            } else {
                $result = $this->model->with('borrows')
                    ->where('title', 'like', "%$query%")
                    ->orderBy('order')
                    ->orderBy('updated_at','desc')
                    ->orderBy('id', 'desc');
            }
        }

        return $result;
    }

    public function show($id)
    {
        $book = $this->find($id);

        if (!$book)
            return $this->responseFail(404, '书籍信息不正确');

        return $book;
    }


    public function store($request)
    {
        $donation_account = $request->donation_account;
        if(isset($donation_account)){
            $account = \App\Models\Mgt\User::where('account', $donation_account)->first();
            if(!$account)
                return $this->responseFail(404,'用户账号信息不正确');
        }

        $book = $this->create([
            'title' => $request->title,
            'isbn' => $request->isbn,
            'bookcase' => $request->bookcase,
            'bookshelf' => $request->bookshelf,
            'bookcategory' => $request->bookcategory,
            'dbid' => $request->dbid,
            'branch_id' => $request->branch_id,
            'donation_account' => isset($account)?$account->account:null,
            'donation_uid' => isset($account)?$account->id:null,
            'is_donation' => isset($account)?1:0,
            'isbn10' => $request->isbn10,
            'isbn13' => $request->isbn13,
            'author' => $request->author,
            'origin_title' => $request->origin_title,
            'subtitle' => $request->subtitle,
            'url' => $request->url,
            'image' => $request->image,
            'translator' => $request->translator,
            'publisher' => $request->publisher,
            'pubdate' => $request->pubdate,
            'binding' => $request->binding,
            'price' => $request->price,
            'pages' => $request->pages,
            'series' => $request->series,
            'author_intro' => $request->author_intro,
            'summary' => $request->summary,
            'catalog' => $request->catalog,
        ]);

        if (!!$book) {
            $imgurl = $request->image;

            $fn = $request->dbid . '.jpg';
            $curl = new Curl(PATH_BOOKCOVER);
            $curl->getFile($imgurl, $fn);
            return $this->responseSuccess('增加书籍信息成功', $book, route('book.create'));
        }

        return $this->responseFail(500, '增加书籍信息失败');
    }


    /**
     * 更新书籍信息
     *
     * @param $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function renew($request, $id)
    {
        $donation_account = $request->donation_account;

        if(isset($donation_account)){
            $account = \App\Models\Mgt\User::where('account', $donation_account)->first();
            if(!$account)
                return $this->responseFail(404,'用户账号信息不正确');
        }

        $result = $this->update([
            'title' => $request->title,
            'isbn' => $request->isbn,
            'bookcase' => $request->bookcase,
            'bookshelf' => $request->bookshelf,
            'bookcategory' => $request->bookcategory,
            'dbid' => $request->dbid,
            'branch_id' => $request->branch_id,
            'donation_account' => isset($account)?$account->account:null,
            'donation_uid' => isset($account)?$account->id:null,
            'is_donation' => isset($account)?1:0,
            'isbn10' => $request->isbn10,
            'isbn13' => $request->isbn13,
            'author' => $request->author,
            'origin_title' => $request->origin_title,
            'subtitle' => $request->subtitle,
            'url' => $request->url,
            'image' => $request->image,
            'translator' => $request->translator,
            'publisher' => $request->publisher,
            'pubdate' => $request->pubdate,
            'binding' => $request->binding,
            'price' => $request->price,
            'pages' => $request->pages,
            'series' => $request->series,
            'author_intro' => $request->author_intro,
            'summary' => $request->summary,
            'catalog' => $request->catalog,
            'order' => isset($request->order)?9:1,
        ], $id);

        if (!!$result) {
            $imgurl = $request->image;

            $fn = $request->dbid . '.jpg';
            $curl = new Curl(PATH_BOOKCOVER);
            $curl->getFile($imgurl, $fn);
            return $this->responseSuccess('更新书籍信息成功');
        }

        return $this->responseFail(500, '更新书籍信息失败');

    }

    public function status($book, $status)
    {
        $this->update([
            'status' => $status,
        ], $book->id);
    }


    public function categories()
    {
        return $this->model->category();
    }

    /**
     * 书籍分类统计
     * @return [type] [description]
     */
    public function bookstore()
    {
        $rows = DB::table('biz_books')
                ->select(DB::raw('bookcategory,COUNT(`id`) as value'))
                ->groupBy('bookcategory')
                ->orderBy('bookcategory')
                ->get();

        $categories = $this->categories();

        $result = $rows->map(function ($item) use ($categories) {

            $item->name = $categories[$item->bookcategory]['name'];

            $item->itemStyle = '{color:"'.$categories[$item->bookcategory]['color'].'"}';

            return $item;
        });
        //dd($result);
        return $result->toArray();
    }

}